package xin.marcher.wind.migrate.service.impl;

import org.springframework.stereotype.Service;
import xin.marcher.wind.migrate.domain.RangeScroll;
import xin.marcher.wind.migrate.domain.entity.ScrollDbConfigDO;
import xin.marcher.wind.migrate.domain.entity.ScrollDomainDO;
import xin.marcher.wind.migrate.domain.entity.ScrollShardConfigDO;
import xin.marcher.wind.migrate.mapper.ScrollDbConfigMapper;
import xin.marcher.wind.migrate.service.MigrateConfigService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 迁移配置获取
 */
@Service
public class MigrateConfigServiceImpl implements MigrateConfigService {

    @Resource
    private ScrollDbConfigMapper scrollDBConfigMapper;

    /**
     * 存储topic对应的配置信息
     */
    private Map<String, RangeScroll> topicMap = new ConcurrentHashMap<>();

    @Override
    public List<ScrollDomainDO> queryScrollDomainList() {
        return scrollDBConfigMapper.queryScrollDomainList();
    }

    @Override
    public List<ScrollDbConfigDO> queryScrollDbConfigList(Long domainId) {
        return scrollDBConfigMapper.queryScrollDbConfigList(domainId);
    }

    @Override
    public List<ScrollShardConfigDO> queryScrollShardConfigList(Long domainId) {
        return scrollDBConfigMapper.queryScrollShardConfigList(domainId);
    }

    @Override
    public List<String> getDomainNames() {
        return scrollDBConfigMapper.getDomainNames();
    }

    @Override
    public List<String> getTablesToDomain(String domain) {
        return scrollDBConfigMapper.getTablesToDomain(domain);
    }

    @Override
    public Long getDomainId(String domain) {
        return scrollDBConfigMapper.getDomainId(domain);
    }

    /**
     * 根据消息主题返回对应的业务系统
     *
     * @param topic
     * @return
     */
    @Override
    public RangeScroll getScrollConfig(String topic) {
        if (topicMap.containsKey(topic)) {
            return topicMap.get(topic);
        }
        ScrollDomainDO dataBaseDomain = scrollDBConfigMapper.getDataBaseDomain(topic);
        // 封装对应的域
        RangeScroll rangeScroll = new RangeScroll();
        rangeScroll.setDomain(dataBaseDomain.getDomain());
        rangeScroll.setDomainId(dataBaseDomain.getId());
        topicMap.put(topic, rangeScroll);
        return rangeScroll;
    }

    @Override
    public String getSourceTableName(String domain, String sourceTableName) {
        return scrollDBConfigMapper.getSourceTableName(domain, sourceTableName);
    }
}
